angular.module('ionicApp', ['ionic',"commentService"])

.config(function($stateProvider, $urlRouterProvider) {

  $stateProvider
    .state('signin', {
      url: "/sign-in",
      templateUrl: "sign-in.html"
    })
    .state('forgotpassword', {
      url: "/forgot-password",
      templateUrl: "forgot-password.html"
    })
    .state('tabs', {
      url: "/tab",
      abstract: true,
      templateUrl: "tabs.html"
    })
    .state('tabs.home', {
      url: "/home",
      views: {
        'home-tab': {
          templateUrl: "home.html"
        }
      }
    })
    .state('tabs.facts', {
      url: "/facts",
      views: {
        'home-tab': {
          templateUrl: "facts.html"
        }
      }
    })
    .state('tabs.facts2', {
      url: "/facts2",
      views: {
        'home-tab': {
          templateUrl: "facts2.html"
        }
      }
    })
    .state('tabs.facts3', {
      url: "/facts3",
      views: {
        'home-tab': {
          templateUrl: "facts3.html"
        }
      }
    })
    .state('tabs.facts4', {
      url: "/facts4",
      views: {
        'home-tab': {
          templateUrl: "facts4.html"
        }
      }
    })
    .state('tabs.facts5', {
      url: "/facts5",
      views: {
        'home-tab': {
          templateUrl: "facts5.html"
        }
      }
    })
    .state('tabs.about', {
      url: "/about",
      views: {
        'about-tab': {
          templateUrl: "about.html"
        }
      }
    })
    .state('tabs.navstack', {
      url: "/navstack",
      views: {
        'about-tab': {
          templateUrl: "nav-stack.html"
        }
      }
    })
    .state('tabs.contact', {
      url: "/contact",
      views: {
        'contact-tab': {
          templateUrl: "contact.html"
        }
      }
    });


   $urlRouterProvider.otherwise("/sign-in");

})


.controller('listcontactCtrl', function($rootScope,$scope, $ionicLoading, $timeout, $http,$ionicModal, $state, User, Contact,Episode, Nursingrecord, Drugchart, Operativerecord) {
$scope.contactrecord = {'id':localStorage.getItem('id_contact'),'fullname':localStorage.getItem('fullname'),'dob':localStorage.getItem('dob'),'avartar':localStorage.getItem('avartar')};
$scope.episodeDetail=JSON.parse(localStorage.getItem('episodeDetail'));
$rootScope.idcontact=localStorage.getItem('id_contact');
$rootScope.display1=localStorage.getItem("display1");
$rootScope.display2=localStorage.getItem("display2");
$rootScope.display3=localStorage.getItem("display3");
$scope.autorefresh = false;
$scope.autorefreshOpe = false;
$scope.leftButton = [
    { 
      type: 'button-clear',
      content: '<a class="button back-button button-icon icon ion-arrow-left-c button back-button button-icon icon ion-arrow-left-c"></a>',
      tap: function(e) {
     window.history.back();
      }
    }
  ]

Contact.get()
  .success(function(data) {
    $scope.autorefresh = false;
    console.log($scope.autorefresh);
    //console.log(data);
    $scope.contacts = data;
  });
$scope.showLoading = function() {
        $scope.loadingIndicator = $ionicLoading.show({
            content: 'Loading...',
            animation: 'fade-in',
            showBackdrop: false,
            maxWidth: 200,
            showDelay: 500
        }); 
    
    $timeout(function(){
      $scope.loadingIndicator.hide();
    },1300);   
  };
  $scope.showLoading2s = function() {
        $scope.loadingIndicator = $ionicLoading.show({
            content: 'Loading...',
            animation: 'fade-in',
            showBackdrop: false,
            maxWidth: 200,
            showDelay: 500
        }); 
    
    $timeout(function(){
      $scope.loadingIndicator.hide();
    },3300);   
  };
  $scope.signOut = function(){
    $scope.autorefresh = false;
        localStorage.clear();
  };
$scope.user = {};
  $scope.signIn = function(){
    $scope.autorefresh = false;
    $scope.showLoading();
    User.login($scope.user).success(function(data){

          if(data > 0 )
          {
            localStorage.setItem('username',$scope.user.username);
    
              localStorage.setItem("display1", "normal");
              localStorage.setItem("display2", "normal");
              localStorage.setItem("display3", "normal");

            $state.go('tabs.home');
          }
          else alert("Username or password is incorrect");
    });
  };
$scope.getLocals =function(){
  return  localStorage.getItem('id_contact');
}


$scope.setLocals = function(){
    localStorage.setItem('id_contact', $scope.contactrecord.id);
    localStorage.setItem('fullname', $scope.contactrecord.fullname);
	localStorage.setItem('dob',$scope.contactrecord.dob);
	localStorage.setItem('avartar',$scope.contactrecord.avartar);
}

//Show Patient Record When click in contact list
$scope.id_contact = {};
$scope.showContact = function(id,fullname,dob,avartar) {
	$scope.id_contact = {'id_contact':id};
  
	//$scope.contactrecord=JSON.parse(localStorage.getItem('contactDetail'));
	$scope.contactrecord ={'id':id,'fullname': fullname,'dob':dob,'avartar':avartar};
	$rootScope.display1=localStorage.getItem("display1");
	$rootScope.display2=localStorage.getItem("display2");
	$rootScope.display3=localStorage.getItem("display3");
  
	//Call Episode Router: function show by id
	Episode.findbycontactid($scope.id_contact)
	.success(function(data) {
		localStorage.setItem('episodeDetail', JSON.stringify(data));
		$scope.episodeDetail=data;
	});


	if(localStorage.getItem('username')=='nurse1'){
		localStorage.setItem("display1", "active");
		localStorage.setItem("display2", "normal");
		localStorage.setItem("display3", "normal");
		$rootScope.display1=localStorage.getItem("display1");
	}
	if(localStorage.getItem('username')=='nurse2'){
		localStorage.setItem("display1", "normal");
		localStorage.setItem("display2", "active");
		localStorage.setItem("display3", "normal");
		$rootScope.display2=localStorage.getItem("display2");
	}
	if(localStorage.getItem('username')=='nurse3'){
		localStorage.setItem("display1", "normal");
		localStorage.setItem("display2", "normal");
		localStorage.setItem("display3", "active");
		$rootScope.display3=localStorage.getItem("display3");
	}
  
  $scope.setLocals(); 
};


$scope.showContact2 = function(id,fullname,dob,avartar) {
	console.log($scope.autorefresh);
	$scope.id_contact = {'id_contact':id};
	$scope.episodeDetail=JSON.parse(localStorage.getItem('episodeDetail'));
	$scope.contactrecord ={'id':id,'fullname': fullname,'dob':dob,'avartar':avartar};
	$rootScope.display1=localStorage.getItem("display1");
	$rootScope.display2=localStorage.getItem("display2");
	$rootScope.display3=localStorage.getItem("display3");
	if(localStorage.getItem('username')=='nurse1'){
		localStorage.setItem("display1", "active");
		localStorage.setItem("display2", "normal");
		localStorage.setItem("display3", "normal");
		$rootScope.display1=localStorage.getItem("display1");
	}
	if(localStorage.getItem('username')=='nurse2'){
		localStorage.setItem("display1", "normal");
		localStorage.setItem("display2", "active");
		localStorage.setItem("display3", "normal");
		$rootScope.display2=localStorage.getItem("display2");
	}
	if(localStorage.getItem('username')=='nurse3'){
		localStorage.setItem("display1", "normal");
		localStorage.setItem("display2", "normal");
		localStorage.setItem("display3", "active");
		$rootScope.display3=localStorage.getItem("display3");
	}
	$scope.setLocals();
   
};
$scope.detailContact = function(id) {
  $scope.autorefresh = false;
  
  Contact.show(id).success(function(data){
      $scope.contactrecord = data;
  });
};

$scope.nurserecord={};
$scope.id_contact = {};
  $scope.checkRecord = function(id) {
 
    $scope.nurserecord={};
       $scope.id_contact = {'id_contact':id};

       //console.log($scope.id_contact);
        Nursingrecord.checkrecord($scope.id_contact).success(function(data){
          if(data.length>0)
          {
            if(localStorage.getItem('username')!='nurse1'){
               $scope.nurserecord = {'disabled':"disabled",'id':data[0].id,'id_contact':data[0].id_contact,'rectime':data[0].rectime,'vertime':data[0].vertime,'eyetime':data[0].eyetime,'vertime1':data[0].vertime1,'pretime':data[0].pretime,'bp':data[0].bp,'pul':data[0].pul,'iop':data[0].iop,'asc':data[0].asc,'cul':data[0].cul,'che':data[0].che,'phy':data[0].phy,'cas':data[0].cas};
            }else{
              $scope.nurserecord = {'id':data[0].id,'id_contact':data[0].id_contact,'rectime':data[0].rectime,'vertime':data[0].vertime,'eyetime':data[0].eyetime,'vertime1':data[0].vertime1,'pretime':data[0].pretime,'bp':data[0].bp,'pul':data[0].pul,'iop':data[0].iop,'asc':data[0].asc,'cul':data[0].cul,'che':data[0].che,'phy':data[0].phy,'cas':data[0].cas};
            }

          };
    });
};


$scope.rightNurseButton = [
  { 
    type: 'button-clear',
    content: 'Done',
    tap: function(e) {
    if($scope.nurserecord.id_contact!=null)
    {
	console.log($scope.nurserecord);
      Nursingrecord.update($scope.nurserecord.id,$scope.nurserecord).success(function(data){
        alert('Update success');
      });
    }
    else 
    {

        $scope.nurserecord_temp={'id_contact':$scope.contactrecord.id,'rectime':$scope.nurserecord.rectime,'vertime':$scope.nurserecord.vertime,'eyetime':$scope.nurserecord.eyetime,'vertime1':$scope.nurserecord.vertime1,'pretime':$scope.nurserecord.pretime,'bp':$scope.nurserecord.bp,'pul':$scope.nurserecord.pul,'iop':$scope.nurserecord.iop,'asc':$scope.nurserecord.asc,'cul':$scope.nurserecord.cul,'che':$scope.nurserecord.che,'phy':$scope.nurserecord.phy,'cas':$scope.nurserecord.cas};
       console.log($scope.nurserecord_temp);
        Nursingrecord.save($scope.nurserecord_temp).success(function(data){
        alert('Create success');
      
      });
    }
    }
  }
  ]


$scope.drugchart={};
$scope.id_contact = {};
  $scope.checkDrugchart = function(id) {
 
    $scope.drugchart={};
        //$scope.nurserecord_temp={'id_contact':id,'rectime':$scope.nurserecord.rectime,'vertime':$scope.nurserecord.vertime,'eyetime':$scope.nurserecord.eyetime,'vertime1':$scope.nurserecord.vertime1,'pretime':$scope.nurserecord.pretime,'bp':$scope.nurserecord.bp,'pul':$scope.nurserecord.pul,'iop':$scope.nurserecord.iop,'asc':$scope.nurserecord.asc,'cul':$scope.nurserecord.cul,'che':$scope.nurserecord.che,'phy':$scope.nurserecord.phy,'cas':$scope.nurserecord.cas};
       //console.log($scope.nurserecord_temp);
       $scope.id_contact = {'id_contact':id};
       //console.log($scope.id_contact);
        Drugchart.checkdrugchart($scope.id_contact).success(function(data){
          if(data.length>0)
          {
            if(localStorage.getItem('username')!='nurse2'){
              $scope.drugchart = {'disabled':"disabled",'id':data[0].id,'id_contact':id,'dia':data[0].dia,'hyp':data[0].hyp,'car':data[0].car,'ast':data[0].ast,'ren':data[0].ren,'oth':data[0].oth,'all':data[0].all,'dru':data[0].dru};
            }
            else $scope.drugchart = {'id':data[0].id,'id_contact':id,'dia':data[0].dia,'hyp':data[0].hyp,'car':data[0].car,'ast':data[0].ast,'ren':data[0].ren,'oth':data[0].oth,'all':data[0].all,'dru':data[0].dru};
          }
    });
};

$scope.rightDrugButton = [
  { 
    type: 'button-clear',
    content: 'Done',
    tap: function(e) {
      if($scope.drugchart.id_contact!=null)
      {
        //console.log('goi ham update');
        Drugchart.update($scope.drugchart.id,$scope.drugchart).success(function(data){
          alert('Update success');
        });
      }
      else
      {
            $scope.drugchart_temp={'id_contact':$scope.contactrecord.id,'dia':$scope.drugchart.dia,'hyp':$scope.drugchart.hyp,'car':$scope.drugchart.car,'ast':$scope.drugchart.ast,'ren':$scope.drugchart.ren,'oth':$scope.drugchart.oth,'all':$scope.drugchart.all,'dru':$scope.drugchart.dru};
           //console.log($scope.drugchart_temp);
            Drugchart.save($scope.drugchart_temp).success(function(data){
            //console.log(data);
            alert('Create success');
        });
      }
    }
  }
  ]


$scope.pre={};
$scope.id_contact = {};
  $scope.checkOpe = function(id) {
  $scope.autorefreshOpe = true;
 
    $scope.pre={};
        //$scope.nurserecord_temp={'id_contact':id,'rectime':$scope.nurserecord.rectime,'vertime':$scope.nurserecord.vertime,'eyetime':$scope.nurserecord.eyetime,'vertime1':$scope.nurserecord.vertime1,'pretime':$scope.nurserecord.pretime,'bp':$scope.nurserecord.bp,'pul':$scope.nurserecord.pul,'iop':$scope.nurserecord.iop,'asc':$scope.nurserecord.asc,'cul':$scope.nurserecord.cul,'che':$scope.nurserecord.che,'phy':$scope.nurserecord.phy,'cas':$scope.nurserecord.cas};
       //console.log($scope.nurserecord_temp);
       $scope.id_contact = {'id_contact':id};
       //console.log($scope.id_contact);
        Operativerecord.checkpre($scope.id_contact).success(function(data){
          if(data.length>0)
          {
            if(localStorage.getItem('username')!='nurse3'){
              $scope.pre = {'disabled':"disabled",'id':data[0].id,'id_contact':id,'re_ucv':data[0].re_ucv,'re_bcv':data[0].re_bcv,'le_ucv':data[0].le_ucv,'le_bcv':data[0].le_bcv,'nsi':data[0].nsi,'bro':data[0].bro,'nsii':data[0].nsii,'tra':data[0].tra,'nsiii':data[0].nsiii,'pen':data[0].pen,'nsiv':data[0].nsiv,'sub':data[0].sub,'psc':data[0].psc,'pha':data[0].pha,'ppc':data[0].ppc,'pha1':data[0].pha1,'cor':data[0].cor,'aph':data[0].aph,'mat':data[0].mat,'pse':data[0].pse,'hyp':data[0].hyp,'oth':data[0].oth,'sign':data[0].sign};
            }
            else  $scope.pre = {'id':data[0].id,'id_contact':id,'re_ucv':data[0].re_ucv,'re_bcv':data[0].re_bcv,'le_ucv':data[0].le_ucv,'le_bcv':data[0].le_bcv,'nsi':data[0].nsi,'bro':data[0].bro,'nsii':data[0].nsii,'tra':data[0].tra,'nsiii':data[0].nsiii,'pen':data[0].pen,'nsiv':data[0].nsiv,'sub':data[0].sub,'psc':data[0].psc,'pha':data[0].pha,'ppc':data[0].ppc,'pha1':data[0].pha1,'cor':data[0].cor,'aph':data[0].aph,'mat':data[0].mat,'pse':data[0].pse,'hyp':data[0].hyp,'oth':data[0].oth,'sign':data[0].sign};
          };
    });
};

$scope.initHome =function(){
  Contact.get()
  .success(function(data) {
    $scope.autorefresh = false;
    console.log($scope.autorefresh);
    //console.log(data);
    $scope.contacts = data;
  });
}

$scope.initDetailcontact =function(){
  $scope.autorefresh = false;
  console.log($scope.autorefresh);
  console.log('da init initDetailcontact');
  console.log($scope.getLocals());
  $scope.detailContact($scope.getLocals());
}
$scope.initNursingRecord =function(){
  $scope.autorefresh = false;
  console.log($scope.autorefresh);
  console.log('da init nurse');
  console.log($scope.getLocals());
  $scope.checkRecord($scope.getLocals());
}

$scope.initDrugchart =function(){
  $scope.autorefresh = false;
  console.log($scope.autorefresh);
  console.log('da init initDrugchart');
  console.log($scope.getLocals());
  $scope.checkDrugchart($scope.getLocals());
}
$scope.initOpe =function(){
  if($scope.autorefreshOpe == true)
  {
	location.reload(); 
  }
  $scope.autorefreshOpe = false;
  $scope.autorefresh = false;
  console.log($scope.autorefresh);
  console.log('da init initOpe');
  console.log($scope.getLocals());
 
  $scope.checkOpe($scope.getLocals());
}
var refreshRules = function() {
  if($scope.autorefresh == true)
  {
    $timeout(refreshRules, 5000);
    console.log('lan 1');
    $scope.showContact2(localStorage.getItem('id_contact'),localStorage.getItem('fullname'),localStorage.getItem('dob'),localStorage.getItem('avartar'));
  }
};


$scope.initRules =function(){
  console.log('da init rule');
  $scope.autorefresh = true;
  console.log($scope.autorefresh);
  $scope.showContact(localStorage.getItem('id_contact'),localStorage.getItem('fullname'),localStorage.getItem('dob'),localStorage.getItem('avartar'));
  if($scope.autorefresh == true)
    refreshRules();
}

$scope.addTime = function(id) {
    var d = new Date();
    console.log();
    //var today = d.getFullYear()+"-"+(d.getMonth()+1)+"-"+d.getDate()+" "+d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();
    var today = d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();
    if(id==1){  
      $scope.nurserecord.rectime=today;
    } 
    if(id==2){  
      $scope.nurserecord.vertime=today;
    } 
    if(id==3){  
      $scope.nurserecord.eyetime=today;
    }
    if(id==4){  
      $scope.nurserecord.vertime1=today;
    }
    if(id==5){  
      $scope.nurserecord.pretime=today;
    } 
  };
  $scope.addDate = function() {
    var d = new Date();
    console.log();
    //var today = d.getFullYear()+"-"+(d.getMonth()+1)+"-"+d.getDate()+" "+d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();
    var today = d.getFullYear()+"-"+(d.getMonth()+1)+"-"+d.getDate(); 
      $scope.nurserecord.date=today;
  };
$scope.rightOpeButton = [
  { 
    type: 'button-clear',
    content: 'Done',
    tap: function(e) {
         //console.log($scope.pre);
      if($scope.pre.id_contact!=null)
      {
        //console.log('goi ham update');
		$scope.pre.sign=$("#dsds").attr("src");
        Operativerecord.update($scope.pre.id,$scope.pre).success(function(data){
          alert('Update success');
        });
      }
      else
      {
	  var dsds=$("#dsds").attr("src");
          $scope.pre_temp={'id_contact':$scope.contactrecord.id,'re_ucv':$scope.pre.re_ucv,'re_bcv':$scope.pre.re_bcv,'le_ucv':$scope.pre.le_ucv,'le_bcv':$scope.pre.le_bcv,'nsi':$scope.pre.nsi,'bro':$scope.pre.bro,'nsii':$scope.pre.nsii,'tra':$scope.pre.tra,'nsiii':$scope.pre.nsiii,'pen':$scope.pre.pen,'nsiv':$scope.pre.nsiv,'sub':$scope.pre.sub,'psc':$scope.pre.psc,'pha':$scope.pre.pha,'ppc':$scope.pre.ppc,'pha1':$scope.pre.pha1,'cor':$scope.pre.cor,'aph':$scope.pre.aph,'mat':$scope.pre.mat,'pse':$scope.pre.pse,'hyp':$scope.pre.hyp,'oth':$scope.pre.oth,'sign':dsds};
         //console.log($scope.pre_temp);
          Operativerecord.save($scope.pre_temp).success(function(data){
          //console.log(data);
          alert('Create success');
        });
      }
    }
  }
  ]
  $ionicModal.fromTemplateUrl('modal.html', function($ionicModal) {
        $scope.modal = $ionicModal;
    }, {
        // Use our scope for the scope of the modal to keep it simple
        scope: $scope,
        // The animation we want to use for the modal entrance
        animation: 'slide-in-up'
    });  

  $scope.hidePopupSign = function(){
    $("#popUpDiv").hide();
	$("#blanket").hide();
  };
    $scope.showPopup = function(){
	$('#popUpDiv').show();
	popup('popUpDiv');
  };
  
    $scope.hidePopupImage = function(){
    $("#popUpDivImage").hide();
	$("#blanket").hide();
  };
  
  $scope.showPopupImage = function(){

	var x=$('.dropshadowclass').offset();
	document.getElementById("popUpDivImage").style.top=x.top+100;
	document.getElementById("popUpDivImage").style.left=$(window).width()/2-180;
	$('#popUpDivImage').show();
	popup('popUpDivImage');
  };
})
.controller('HomeTabCtrl', function($scope, $ionicModal) {
  console.log('HomeTabCtrl');
  
    // Load the modal from the given template URL
    
});
